import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Space,
  message,
  Spin,
  Select,
  DatePicker,
  Row,
  Col
} from 'antd';
import {
  ArrowLeftOutlined,
  SaveOutlined,
  UserOutlined
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import moment from 'moment';

const { Option } = Select;
const { TextArea } = Input;

const TeacherEdit = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { isAdmin } = useAuth();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [teacher, setTeacher] = useState(null);
  const isEdit = !!id;

  useEffect(() => {
    if (!isAdmin()) {
      message.error('权限不足');
      navigate('/teachers');
      return;
    }

    if (isEdit) {
      loadTeacherDetail();
    }
  }, [id, isAdmin, navigate, isEdit]);

  const loadTeacherDetail = async () => {
    try {
      setLoading(true);
      const data = await apiService.getTeacherById(id);
      setTeacher(data);
      
      // 填充表单数据
      form.setFieldsValue({
        ...data,
        birthDate: data.birthDate ? moment(data.birthDate) : null,
        hireDate: data.hireDate ? moment(data.hireDate) : null
      });
    } catch (error) {
      message.error('加载教师信息失败');
      console.error('加载教师信息失败:', error);
      navigate('/teachers');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (values) => {
    try {
      setSubmitting(true);
      
      const submitData = {
        ...values,
        birthDate: values.birthDate ? values.birthDate.format('YYYY-MM-DD') : null,
        hireDate: values.hireDate ? values.hireDate.format('YYYY-MM-DD') : null
      };

      if (isEdit) {
        await apiService.updateTeacher(id, submitData);
        message.success('教师信息更新成功');
      } else {
        await apiService.createTeacher(submitData);
        message.success('教师创建成功');
      }
      
      navigate('/teachers');
    } catch (error) {
      const errorMessage = error.response?.data?.message || error.message;
      message.error(isEdit ? `更新教师信息失败：${errorMessage}` : `创建教师失败：${errorMessage}`);
      console.error('提交失败:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const handleCancel = () => {
    navigate('/teachers');
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={handleCancel}
        >
          返回教师列表
        </Button>
      </div>

      <Card
        title={
          <Space>
            <UserOutlined />
            {isEdit ? '编辑教师' : '新建教师'}
          </Space>
        }
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            gender: 'MALE',
            title: '讲师'
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="姓名"
                name="name"
                rules={[
                  { required: true, message: '请输入姓名' },
                  { min: 2, max: 20, message: '姓名长度应在2-20个字符之间' }
                ]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="性别"
                name="gender"
                rules={[{ required: true, message: '请选择性别' }]}
              >
                <Select placeholder="请选择性别">
                  <Option value="MALE">男</Option>
                  <Option value="FEMALE">女</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="邮箱"
                name="email"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="电话"
                name="phone"
                rules={[
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
                ]}
              >
                <Input placeholder="请输入电话号码" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="院系"
                name="department"
                rules={[
                  { required: true, message: '请输入院系' },
                  { max: 50, message: '院系名称不能超过50个字符' }
                ]}
              >
                <Input placeholder="请输入院系" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="职称"
                name="title"
                rules={[{ required: true, message: '请选择职称' }]}
              >
                <Select placeholder="请选择职称">
                  <Option value="教授">教授</Option>
                  <Option value="副教授">副教授</Option>
                  <Option value="讲师">讲师</Option>
                  <Option value="助教">助教</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="出生日期"
                name="birthDate"
              >
                <DatePicker
                  style={{ width: '100%' }}
                  placeholder="请选择出生日期"
                  format="YYYY-MM-DD"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="入职时间"
                name="hireDate"
              >
                <DatePicker
                  style={{ width: '100%' }}
                  placeholder="请选择入职时间"
                  format="YYYY-MM-DD"
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="地址"
            name="address"
            rules={[
              { max: 200, message: '地址不能超过200个字符' }
            ]}
          >
            <Input placeholder="请输入地址" />
          </Form.Item>

          <Form.Item
            label="个人简介"
            name="bio"
            rules={[
              { max: 500, message: '个人简介不能超过500个字符' }
            ]}
          >
            <TextArea
              rows={4}
              placeholder="请输入个人简介"
            />
          </Form.Item>

          {!isEdit && (
            <Row>
              <Col span={12}>
                <Form.Item
                  label="账号"
                  name="username"
                  rules={[
                    { required: true, message: '请输入账号' },
                    { min: 5, message: '账号至少5位' }
                  ]}
                >
                  <Input placeholder="请输入账号" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="密码"
                  name="password"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码至少6位' }
                  ]}
                >
                  <Input.Password placeholder="请输入密码" />
                </Form.Item>
              </Col>
            </Row>
          )}

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SaveOutlined />}
                loading={submitting}
              >
                {isEdit ? '更新' : '创建'}
              </Button>
              <Button onClick={handleCancel}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default TeacherEdit;